<template>
  <div class="address-edit-page">
    <van-nav-bar
      :title="isEdit ? '编辑地址' : '新增地址'"
      left-arrow
      @click-left="goBack"
      fixed
    />
    
    <div class="form-container">
      <van-cell-group inset class="form-group">
        <van-address-edit
          :area-list="areaList"
          :address-info="formData"
          :show-postal="true"
          :show-delete="isEdit"
          :show-set-default="true"
          @save="onSave"
          @delete="onDelete"
          @cancel="onCancel"
          :is-saving="isSaving"
          :is-deleting="isDeleting"
          :area-columns-placeholder="['请选择省', '请选择市', '请选择区']"
          show-area
          :validator="validator"
          :tel-maxlength="11"
        />
      </van-cell-group>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import api from '../network/api';
import { showToast, showDialog } from 'vant';
import { areaList } from '@vant/area-data';

// 定义地址接口
interface Address {
  id: number;
  name: string;
  phone: string;
  provinceCode: string;
  provinceName: string;
  cityCode: string;
  cityName: string;
  districtCode: string;
  districtName: string;
  streetCode: string;
  streetName: string;
  detail: string;
  type: string;
  isDefault: boolean;
  postalCode?: string;
}

// 静态地址数据
const staticAddresses: Address[] = [
  {
    id: 1,
    name: '王小明',
    phone: '13888888888',
    provinceCode: '110000',
    provinceName: '北京市',
    cityCode: '110100',
    cityName: '北京市',
    districtCode: '110105',
    districtName: '朝阳区',
    streetCode: '110105001',
    streetName: '建国门街道',
    detail: '中央公园1号楼2单元502室',
    type: 'home',
    isDefault: true,
    postalCode: '100000'
  },
  {
    id: 2,
    name: '王小明',
    phone: '13888888888',
    provinceCode: '110000',
    provinceName: '北京市',
    cityCode: '110100',
    cityName: '北京市',
    districtCode: '110108',
    districtName: '海淀区',
    streetCode: '110108001',
    streetName: '中关村街道',
    detail: '创业大厦15层1503室',
    type: 'company',
    isDefault: false,
    postalCode: '100080'
  },
  {
    id: 3,
    name: '王小明',
    phone: '13888888888',
    provinceCode: '350000',
    provinceName: '福建省',
    cityCode: '350200',
    cityName: '厦门市',
    districtCode: '350211',
    districtName: '集美区',
    streetCode: '',
    streetName: '',
    detail: '街道门牌、楼层房间号等信息',
    type: 'other',
    isDefault: false,
    postalCode: '361000'
  }
];

export default defineComponent({
  name: 'AddressEditView',
  
  setup() {
    const router = useRouter();
    const route = useRoute();
    const useStaticData = true; // 是否使用静态数据
    const isSaving = ref(false);
    const isDeleting = ref(false);
    
    // 判断是编辑还是新增
    const addressId = computed(() => {
      const id = route.params.id;
      return id ? parseInt(id as string) : null;
    });
    
    const isEdit = computed(() => !!addressId.value);
    
    // 表单数据
    const formData = ref<Record<string, any>>({});
    
    // 获取地址详情
    const getAddressDetail = async () => {
      if (!addressId.value) {
        // 新增地址，设置空表单
        formData.value = {
          name: '',
          tel: '',
          province: '',
          city: '',
          county: '',
          addressDetail: '',
          areaCode: '',
          postalCode: '',
          isDefault: false
        };
        return;
      }
      
      try {
        if (useStaticData) {
          // 使用静态数据
          const address = staticAddresses.find(addr => addr.id === addressId.value);
          if (address) {
            // 转换为 Vant AddressEdit 需要的格式
            formData.value = {
              id: address.id,
              name: address.name,
              tel: address.phone,
              province: address.provinceName,
              city: address.cityName,
              county: address.districtName,
              addressDetail: address.detail,
              areaCode: address.districtCode,
              postalCode: address.postalCode || '',
              isDefault: address.isDefault
            };
          } else {
            showToast('未找到该地址');
            router.back();
          }
        } else {
          // 使用API接口获取数据
          const response = await api.getUserAddresses();
          const address = response.data.find((addr: Address) => addr.id === addressId.value);
          if (address) {
            formData.value = {
              id: address.id,
              name: address.name,
              tel: address.phone,
              province: address.provinceName,
              city: address.cityName,
              county: address.districtName,
              addressDetail: address.detail,
              areaCode: address.districtCode,
              postalCode: address.postalCode || '',
              isDefault: address.isDefault
            };
          } else {
            showToast('未找到该地址');
            router.back();
          }
        }
      } catch (error) {
        console.error('获取地址详情失败', error);
        showToast('获取地址详情失败');
      }
    };
    
    // 保存地址
    const onSave = async (content: any) => {
      try {
        isSaving.value = true;
        
        // 将Vant格式转换为API需要的格式
        const addressData = {
          name: content.name,
          phone: content.tel,
          provinceCode: content.areaCode.substr(0, 2) + '0000',
          provinceName: content.province,
          cityCode: content.areaCode.substr(0, 4) + '00',
          cityName: content.city,
          districtCode: content.areaCode,
          districtName: content.county,
          streetCode: '',
          streetName: '',
          detail: content.addressDetail,
          postalCode: content.postalCode,
          type: 'home', // 默认类型
          isDefault: content.isDefault
        };
        
        if (!useStaticData) {
          if (isEdit.value && addressId.value) {
            await api.updateAddress(addressId.value, addressData);
          } else {
            await api.addAddress(addressData);
          }
        }
        
        showToast('保存成功');
        router.replace('/address');
      } catch (error) {
        console.error('保存地址失败', error);
        showToast('保存地址失败');
      } finally {
        isSaving.value = false;
      }
    };
    
    // 删除地址
    const onDelete = async () => {
      if (!addressId.value) return;
      
      try {
        isDeleting.value = true;
        
        try {
          await showDialog({
            title: '提示',
            message: '确定要删除这个地址吗？',
            showCancelButton: true
          });
        } catch (e) {
          isDeleting.value = false;
          if (e === 'cancel') return; // 用户取消操作
          throw e;
        }
        
        if (!useStaticData) {
          await api.deleteAddress(addressId.value);
        }
        
        showToast('删除成功');
        router.back();
      } catch (error) {
        console.error('删除地址失败', error);
        showToast('删除地址失败');
      } finally {
        isDeleting.value = false;
      }
    };
    
    // 取消
    const onCancel = () => {
      router.back();
    };
    
    // 表单验证器
    const validator = (key: string, value: string) => {
      if (key === 'name' && !value) {
        return '请填写收货人姓名';
      }
      if (key === 'tel' && !/^1[3-9]\d{9}$/.test(value)) {
        return '请填写正确的手机号码';
      }
      if (key === 'addressDetail' && !value) {
        return '请填写详细地址';
      }
      if (key === 'areaCode' && !value) {
        return '请选择地区';
      }
      return '';
    };
    
    // 返回上一页
    const goBack = () => {
      router.back();
    };
    
    onMounted(() => {
      getAddressDetail();
    });
    
    return {
      isEdit,
      formData,
      areaList,
      isSaving,
      isDeleting,
      onSave,
      onDelete,
      onCancel,
      validator,
      goBack
    };
  }
});
</script>

<style scoped>
.address-edit-page {
  background-color: #f7f8fa;
  min-height: 100vh;
}

.form-container {
  padding-top: 46px;
}

.form-group {
  margin-top: 12px;
}

/* 覆盖Vant组件样式 */
:deep(.van-address-edit) {
  padding-top: 0;
}

:deep(.van-address-edit__buttons) {
  padding: 30px 15px;
}

:deep(.van-button--primary) {
  background-color: #3490dc;
  border-color: #3490dc;
}
</style> 